package com.stu.view;


import com.stu.dao.StudentDao;
import com.stu.model.Student;
import com.stu.util.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Objects;

/**
 * @author Fairy
 */
public class AddStudent extends JInternalFrame {
	private final JTextField addNameTextField;
	private final JTextField addScoreTextField;

	/**
	 * 布局
	 */
	public AddStudent() {
		setTitle("添加学生");
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(null);
		setClosable(true);
		//内部窗体添加关闭最小化
		setIconifiable(true);
		
		JPanel addNamePanel = new JPanel();
		addNamePanel.setBounds(14, 52, 406, 38);
		getContentPane().add(addNamePanel);
		
		JLabel addNameLabel = new JLabel("姓名：");
		addNameLabel.setIcon(new ImageIcon(Objects.requireNonNull(AddStudent.class.getResource("/img/姓名.png"))));
		addNameLabel.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
		addNamePanel.add(addNameLabel);

		addNameTextField = new JTextField();
		addNameTextField.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
		addNamePanel.add(addNameTextField);
		addNameTextField.setColumns(15);
		
		JPanel addScorePanel = new JPanel();
		addScorePanel.setBounds(14, 115, 263, 38);
		getContentPane().add(addScorePanel);
		
		JLabel addScoreLabel = new JLabel("成绩：");
		addScoreLabel.setIcon(new ImageIcon(Objects.requireNonNull(AddStudent.class.getResource("/img/成绩.png"))));
		addScoreLabel.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
		addScorePanel.add(addScoreLabel);

		addScoreTextField = new JTextField();
		addScoreTextField.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
		addScorePanel.add(addScoreTextField);
		addScoreTextField.setColumns(5);
		
		JPanel addSubmitPanel = new JPanel();
		addSubmitPanel.setBounds(14, 184, 406, 38);
		getContentPane().add(addSubmitPanel);
		 
		JButton submitButton = new JButton("提交");
		submitButton.addActionListener(this::addstu);
		submitButton.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
		addSubmitPanel.add(submitButton);
	}

	/**
	 * 添加学生
	 */
	protected void addstu(ActionEvent e) {
		String stuname = addNameTextField.getText();
		String stuscore = addScoreTextField.getText();
		
		if (StringUtil.isEmpty(stuname)) {
			JOptionPane.showMessageDialog(this, "学生姓名为空！");
			return;
		}
		if (StringUtil.isEmpty(stuscore)) {
			JOptionPane.showMessageDialog(this, "成绩为空！");
			return;
		}
		
		Student student = new Student();
		student.setName(stuname);
		student.setScore(stuscore);
		
		StudentDao studentDao = new StudentDao();
		if (studentDao.add(student)) {
			JOptionPane.showMessageDialog(this, "添加成功！");
		}else {
			JOptionPane.showMessageDialog(this, "添加失败！");
		}
		
		reset();//清空文本框
		
	}

	/**
	 * 清空文本框
	 */
	private void reset() {
		addNameTextField.setText("");
		addScoreTextField.setText("");
	}

}
